package com.sailfish.springbootdemo.controller.db7;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db7.TbTemplateDao;
import com.sailfish.springbootdemo.dao.db7.TbTemplateVersionDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db5.ToolManagement;
import com.sailfish.springbootdemo.pojo.db7.*;
import com.sailfish.springbootdemo.service.db7.CommonService;
import com.sailfish.springbootdemo.service.db7.QueryKnowledgeBaseDataService;
import com.sailfish.springbootdemo.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/knowledgeBase")
public class KnowledgeBaseController {

    @Autowired
    private QueryKnowledgeBaseDataService queryKnowledgeBaseDataService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private TbTemplateDao tbTemplateDao;
    @Autowired
    private TbTemplateVersionDao tbTemplateVersionDao;
    @PostMapping("/getParamKeysByVersion")
    public Result getParamKeys(@RequestBody String data)
    {
        try {
            JSONObject dataObj = JSON.parseObject(data);
            String templateType = dataObj.getString("templateType");
            List<TbTemplateVersion> latestV = tbTemplateVersionDao.getNewestTemplateVersion(templateType);

            if(latestV.isEmpty()){
                return ResultUtil.error(500, "规范模板错误", "design template error", null);
            }
            TbTemplateVersion latestVersion = latestV.get(0);
            String version = latestVersion.getVersion();
            List<TbTemplate> paramKeysOfTemplate =
            tbTemplateDao.getTbTemplateByVersion(templateType, version);
            return ResultUtil.success(paramKeysOfTemplate);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/transParamKeyToRealValue")
    public Result transParamKeyToRealValue(@RequestBody String data)
    {
        try {
            JSONObject dataObj = JSON.parseObject(data);
            String flowNo = dataObj.getString("flow_no");
            JSONArray origin = dataObj.getJSONArray("origin");
            String templateType = dataObj.getString("templateType");
            return queryKnowledgeBaseDataService.queryRealValueByKey(flowNo, templateType, origin);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/getRuleDetails")
    public Result getRuleDetails(@RequestBody String data)
    {
        try {
            JSONObject dataObj = JSON.parseObject(data);
            String baseKey = dataObj.getString("knowledge_base_key");
            return queryKnowledgeBaseDataService.queryDesignRuleDetails(baseKey);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    // 辅助方法：安全获取字符串
    private String getStringOrDefault(Object value, String defaultValue) {
        return value != null && !value.toString().isEmpty() ? value.toString() : defaultValue;
    }

    @PostMapping("/queryToolManagement")
    public Result queryToolManagement(@RequestBody String data)
    {
        try {
            JSONObject dataObject = JSON.parseObject(data);
            ToolManagement entity = new ToolManagement();
            entity.setVer(dataObject.getString("Ver"));
            entity.setCPitem(dataObject.getString("CPitem"));
            entity.setWF_DocCreated(dataObject.getString("WF_DocCreated"));
            entity.setGZitem(dataObject.getString("GZitem"));
            entity.setGZremark(dataObject.getString("GZremark"));
            entity.setGZtype(dataObject.getString("GZtype"));
            entity.setGZdesc(dataObject.getString("GZdesc"));
            Integer page = dataObject.getInteger("page");
            Integer pageSize = dataObject.getInteger("pageSize");
            return queryKnowledgeBaseDataService.queryToolManagement(entity, page, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/importBomExcel")
    public Result importBomExcel(HttpServletRequest req)
    {
        try {
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
            MultipartFile multipartFile = mRequest.getFile("file");

            return queryKnowledgeBaseDataService.importBomExcel(multipartFile);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/importBomExcelInTool")
    public Result importBomExcelInTool(HttpServletRequest req)
    {
        try {
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
            MultipartFile multipartFile = mRequest.getFile("file");
            return queryKnowledgeBaseDataService.importBomExcelInTool(multipartFile);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/getAllDesignPhase")
    public Result getAllDesignPhase(String templateType)
    {
        try {
            return queryKnowledgeBaseDataService.getAllDesignPhase(templateType);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/downloadBomTemplateExcel")
    public Result downloadBomTemplateExcel()
    {

        Result result = queryKnowledgeBaseDataService.downloadBomTemplateExcel();
        try{
            if (result.getCode().equals(200))
            {
                String filepath = (String) result.getData();
                File file = new File(filepath);
                String fname = file.getName();
                byte[] bytedata = null;
                InputStream in = new FileInputStream(file);  //InputStream in = url.openStream();
                bytedata = new byte[in.available()];
                in.read(bytedata);
                in.close();
                Base64.Encoder encoder = Base64.getEncoder();
                String base64 = encoder.encodeToString(bytedata);

                Map<String, Object> map = new HashMap<>();
                map.put("base64", base64);
                map.put("fileName", fname);
                return ResultUtil.success(map);
            } else
            {
                return result;
            }
            }catch (Exception e){
                log.error("error:", e);
                return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }

    }
    @PostMapping("/outPutExcelOfKnowledgeData")
    public Result outPutExcelOfKnowledgeData(@RequestBody String data)
    {
        try {
            JSONObject dataObject = JSON.parseObject(data);
            // 提取conditions
            JSONArray conditionsArray = dataObject.getJSONArray("conditions");
            String searchFlowType = dataObject.getString("flowType");
            String functionUser = dataObject.getString("functionUser");
            String templateType = dataObject.getString("template_type");
            List<Map<String, String>> keyValueMaps = new ArrayList<>();

            if (conditionsArray != null) {
                for (int i = 0; i < conditionsArray.size(); i++) {
                    JSONObject condition = conditionsArray.getJSONObject(i);
                    Map<String, String> map = new HashMap<>();
                    if(StringUtils.isEmpty(condition.getString("key")) && !StringUtils.isEmpty(condition.getString("value")))
                    {
                        return ResultUtil.error(500, "错误的键值对nullkey-to-value", "wrong key-value", null);
                    }
                    map.put("key", condition.getString("key"));
                    map.put("value", condition.getString("value"));
                    keyValueMaps.add(map);
                }
            }
            Integer flag = dataObject.containsKey("functionFlag") ? dataObject.getInteger("functionFlag") : 0;
            Object o = queryKnowledgeBaseDataService.
                    queryKnowledgeDataByLimit(templateType,
                            keyValueMaps,
                            flag,
                            1,
                            99999,
                            functionUser,
                            searchFlowType).getData();

            Map<String, Object> map = new HashMap<>();
            if(o == null)
            {
                map.put("base64", "");
                map.put("fileName", "器件工艺知识库表");
                return ResultUtil.success(map);
            }
            JSONArray rows = (JSONArray) ((Map<String, Object>)o).get("rows");
            Result result;
            if("deviceType".equals(templateType))
            {
                result = queryKnowledgeBaseDataService.outPutExcelOfDeviceData(rows);
            }
            else{
                result = queryKnowledgeBaseDataService.outPutExcelOfDesignData(rows);
            }
            if (result.getCode().equals(200)) {
                String filepath = (String) result.getData();
                File file = new File(filepath);
                String fileName = file.getName();
                byte[] bytedata = null;
                InputStream in = new FileInputStream(file);  //InputStream in = url.openStream();
                bytedata = new byte[in.available()];
                in.read(bytedata);
                in.close();
                Base64.Encoder encoder = Base64.getEncoder();
                String base64 = encoder.encodeToString(bytedata);

                map.put("base64", base64);
                map.put("fileName", fileName);
                return ResultUtil.success(map);
            } else {
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/queryTemplateTaskData")
    public Result queryKnowledgeDataByLimit(@RequestBody String data) {
        try
        {
            JSONObject dataObject = JSON.parseObject(data);
            // 提取conditions
            JSONArray conditionsArray = dataObject.getJSONArray("conditions");
            int page = dataObject.getInteger("page");
            int pageSize = dataObject.getInteger("pageSize");
            List<Map<String, String>> keyValueMaps = new ArrayList<>();

            if (conditionsArray != null) {
                for (int i = 0; i < conditionsArray.size(); i++) {
                    JSONObject condition = conditionsArray.getJSONObject(i);
                    Map<String, String> map = new HashMap<>();
                    if(StringUtils.isEmpty(condition.getString("key")) &&
                            !StringUtils.isEmpty(condition.getString("value")))
                    {
                        return ResultUtil.error(500, "错误的键值对nullkey-to-value", "wrong key-value", null);
                    }
                    map.put("key", condition.getString("key"));
                    map.put("value", condition.getString("value"));
                    keyValueMaps.add(map);
                }
            }
            String templateType = dataObject.containsKey("templateType") ? dataObject.getString("templateType") : null;
            Integer flag = dataObject.containsKey("functionFlag") ? dataObject.getInteger("functionFlag") : 0;
            String functionUser = dataObject.getString("functionUser");
            String flowType = dataObject.getString("flowType");
            return queryKnowledgeBaseDataService.queryKnowledgeDataByLimit(templateType, keyValueMaps, flag,
                    page, pageSize, functionUser, flowType);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error : ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/queryKnowledgeBaseFile")
    public Result queryKnowledgeBaseFile(@RequestBody String data) {
        try
        {
            JSONObject dataObject = JSON.parseObject(data);
            // 提取编码和封装信息
            String paramValue = dataObject.getString("file_param_value");
            return ResultUtil.success(queryKnowledgeBaseDataService.transferByFileParamKey(paramValue));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error : ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
    @PostMapping("/queryDeviceData")
    public Result queryDeviceData(@RequestBody String data) {
        try
        {
            JSONObject dataObject = JSON.parseObject(data);
            // 提取编码和封装信息
            JSONArray bomParams = dataObject.getJSONArray("bomParams");
            int page = dataObject.getInteger("page");
            int pageSize = dataObject.getInteger("pageSize");
            List<Map<String, String>> bomParamList = new ArrayList<>();
            if (bomParams != null) {
                for (Object o : bomParams) {
                    JSONObject bomParam = (JSONObject) o;
                    Map<String, String> bomParamMap = new HashMap<>();
                    bomParamMap.put("partNo", bomParam.getString("partNo"));
                    bomParamMap.put("posNo", bomParam.getString("posNo"));
                    bomParamMap.put("packageName", bomParam.getString("packageName"));
                    bomParamList.add(bomParamMap);
                }
            }
            return queryKnowledgeBaseDataService.queryDeviceData(bomParamList, page, pageSize,null );
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error : ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/getAllTemplateDataParamList")
    public Result getAllTemplateDataParamList(@RequestBody String data) {
        try
        {
            JSONObject templateTypeObject = JSONObject.parseObject(data);
            String templateType = templateTypeObject.getString("templateType");
            if(StringUtils.isEmpty(templateType))
            {
                return ResultUtil.error(500, "空的模板类型","empty template", 500);
            }
            List<TbTemplate> allParams = queryKnowledgeBaseDataService.getAllTemplateParams(templateType);
            if(allParams == null)
            {
                return ResultUtil.error(500, "获取所有模板异常", "error occured when request all template", null);
            }
            List<TbTemplate> tree = commonService.buildTree2(allParams);
            List<TbTemplate> ret = queryKnowledgeBaseDataService.getAllBaseTemplateParamList(tree, templateType);
            return ResultUtil.success(ret);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/queryExcipientsData")
    public Result queryExcipientsData(@RequestBody String data) {
        try
        {
            JSONObject dataObject = JSON.parseObject(data);
            // 提取conditions
            JSONArray conditionsArray = dataObject.getJSONArray("conditions");
            List<Map<String, String>> keyValueMaps = new ArrayList<>();
            int page = dataObject.getInteger("page");
            int pageSize = dataObject.getInteger("pageSize");

            if (conditionsArray != null) {
                for (int i = 0; i < conditionsArray.size(); i++) {
                    JSONObject condition = conditionsArray.getJSONObject(i);
                    Map<String, String> map = new HashMap<>();
                    if(StringUtils.isEmpty(condition.getString("key")) && !StringUtils.isEmpty(condition.getString("value")))
                    {
                        return ResultUtil.error(500, "错误的键值对nullkey-to-value", "wrong key-value", null);
                    }
                    map.put("key", condition.getString("key"));
                    map.put("value", condition.getString("value"));
                    keyValueMaps.add(map);
                }
            }
            return queryKnowledgeBaseDataService.queryExcipientsDataBylimit(keyValueMaps, page, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/insertOrUpdate")
    public Result insertOrUpdate(HttpServletRequest req) {
        try {
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
            MultipartFile multipartFile = mRequest.getFile("file");

            return queryKnowledgeBaseDataService.insertOrUpdateToExcipientsDataByExcel(multipartFile, true);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/InsertOrUpdateKnowledgeBaseLogic")
    public Result InsertOrUpdateKnowledgeBaseLogic(@RequestBody String data) {
        try {
            JSONObject dataObject = JSON.parseObject(data);
            JSONArray keyArray = dataObject.getJSONArray("keyList");
            JSONArray logicArray = dataObject.getJSONArray("logics");
            String userId = UserHeaderHolder.getUserId();
            Date now = new Date();

            List<TbKnowledgeBasePushLogic> logics = new ArrayList<>();
            int sort = 0;
            for(Object o : logicArray){
                JSONObject obj = (JSONObject)o;
                TbKnowledgeBasePushLogic logic = new TbKnowledgeBasePushLogic();
                logic.setBoardParamTypeName(obj.getString("boardParamTypeName"));
                logic.setBoardParamName(obj.getString("boardParamName"));
                logic.setBoardParamId(obj.getInteger("boardParamId"));
                logic.setBoardParamKey(obj.getString("boardParamKey"));
                logic.setBoardParamTypeId(obj.getInteger("boardParamTypeId"));
                logic.setLogicRule(obj.getInteger("logicRule"));
                logic.setLogicValue(obj.getString("logicValue"));
                //logic.setLogicGroup(obj.getString("logicGroup"));
                logic.setSort(sort++);
//                logic.setRemark(obj.getString("remark"));
                logic.setCreate_time(now);
                logic.setCreate_user(userId);
                logics.add(logic);
            }
            List<String> baseKeys = convertKeyListToStringList(keyArray, "knowledge_base_key");
            return queryKnowledgeBaseDataService.insertOrUpdateKnowledgeBaseLogic(logics, baseKeys);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/updateIsDefaultPush")
    public Result updateIsDefaultPush(@RequestBody String data) {
        try {
            JSONObject dataObject = JSON.parseObject(data);
            String knowledgeBaseKey = dataObject.getString("knowledge_base_key");
            Integer isDefaultPush = dataObject.getInteger("is_default_push");
            return queryKnowledgeBaseDataService.updateIsDefaultPush(knowledgeBaseKey, isDefaultPush);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
    @PostMapping("/getMergeKnowledgeBaseLogic")
    public Result getMergeKnowledgeBaseLogic(@RequestBody String data) {
        try {
            JSONObject dataObject = JSON.parseObject(data);
            JSONArray keyArray = dataObject.getJSONArray("keyList");
            if(keyArray.isEmpty()){
                return ResultUtil.error(500, "空的knowledge_base_key", "knowledge_base_key list is null", null);
            }
            List<String> baseKeys = convertKeyListToStringList(keyArray, "knowledge_base_key");

            return queryKnowledgeBaseDataService.getMergeKnowledgeBaseLogic(baseKeys);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/getExcipientTemplateParams")
    public Result getExcipientTemplateParams(@RequestBody String data) {
        try {
            JSONObject obj = JSON.parseObject(data);
            Integer status = obj.getInteger("status");
            List<TbTemplate> list = queryKnowledgeBaseDataService.getExcipientTemplateParams(status);
            if(Objects.isNull(list) || list.size() == 0)
            {
                return ResultUtil.success("辅料库参数列表不存在");
            }
            return ResultUtil.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/insertExcipientsParams")
    public Result insertExcipientsParams(@RequestBody String data) {
        try {
            JSONArray jsonArray = JSON.parseArray(data);
            List<TbTemplate> newTemplates = new ArrayList<>();
            String userId = UserHeaderHolder.getUserId();
            Date date = new Date();
            for (Object jsonObject : jsonArray) {
                if (jsonObject instanceof JSONObject)
                {
                    TbTemplate tbTemplate = new TbTemplate();
                    JSONObject json = (JSONObject) jsonObject;
                    // 将 TbDataDictionary 的字段值赋值给 TbTemplate 的字段
                    tbTemplate.setTemplate_type("materialType");
                    tbTemplate.setParam_name(json.getString("param_name"));
                    tbTemplate.setParam_name_en(json.getString("param_name_en"));
                    // 获取当前时间并格式化为 "yyyyMMddHHmmss" 格式的字符串
                    LocalDateTime currentDateTime = LocalDateTime.now();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
                    String formattedDateTime = currentDateTime.format(formatter);

                    // 生成一个 1000 以内的随机数（包括 0 到 9999）
                    int randomNumber = (int) (Math.random() * 10000);

                    // 将时间字符串和随机数拼接起来形成paramKey
                    String paramKey = "key_" + formattedDateTime + String.format("%04d", randomNumber);
                    tbTemplate.setParam_key(paramKey);
                    tbTemplate.setParam_type(json.getInteger("param_type"));
//                    tbTemplate.setLevel(json.getInteger("level"));
//                    tbTemplate.setSelect_level(json.getInteger("select_level"));
                    //tbTemplate.setTip(json.getString("tip"));
                    tbTemplate.setRemark(json.getString("remark"));
                    tbTemplate.setCreate_user(userId);
                    tbTemplate.setCreate_time(date);
                    tbTemplate.setStatus(json.getInteger("status"));
                    tbTemplate.setSort(json.getInteger("sort"));
                    tbTemplate.setIs_value(json.getInteger("isValue"));

                    newTemplates.add(tbTemplate);
                }
            }
            return queryKnowledgeBaseDataService.insertExcipientsParams(newTemplates);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
    @PostMapping("/updateExcipientsParams")
    public Result updateExcipientsParams(@RequestBody String data) {
        try {
            JSONArray jsonArray = JSON.parseArray(data);
            List<TbTemplate> newTemplates = new ArrayList<>();
            String userId = UserHeaderHolder.getUserId();
            Date date = new Date();
            for (Object jsonObject : jsonArray) {
                if (jsonObject instanceof JSONObject)
                {
                    TbTemplate tbTemplate = new TbTemplate();
                    JSONObject json = (JSONObject) jsonObject;
                    // 将 TbDataDictionary 的字段值赋值给 TbTemplate 的字段
                    tbTemplate.setId(json.getInteger("id"));
                    tbTemplate.setTemplate_type("materialType");
                    tbTemplate.setParam_name(json.getString("param_name"));
                    tbTemplate.setParam_name_en(json.getString("param_name_en"));
                    tbTemplate.setParam_key(json.getString("param_key"));
                    tbTemplate.setParam_type(json.getInteger("param_type"));
//                    tbTemplate.setLevel(json.getInteger("level"));
//                    tbTemplate.setSelect_level(json.getInteger("select_level"));
                    //tbTemplate.setTip(json.getString("tip"));
                    tbTemplate.setRemark(json.getString("remark"));
                    tbTemplate.setUpdate_user(userId);
                    tbTemplate.setUpdate_time(date);
                    tbTemplate.setStatus(json.getInteger("status"));
                    tbTemplate.setSort(json.getInteger("sort"));
                    tbTemplate.setIs_value(json.getInteger("isValue"));

                    newTemplates.add(tbTemplate);
                }
            }
            return queryKnowledgeBaseDataService.updateExcipientsParams(newTemplates);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/insertExcipientData")
    public Result insertExcipientData(@RequestBody String data) {
        try {
            String userId = UserHeaderHolder.getUserId();
            Date now = new Date();
            JSONArray jsonArray = JSON.parseArray(data);
            if(Objects.isNull(jsonArray))
            {
                return ResultUtil.error(500, "辅料data为空", "null excipient data", null);
            }
            List<TbExcipientsData> dataList = new ArrayList<>();
            for(Object o : jsonArray )
            {
                if(o instanceof JSONObject)
                {
                    JSONObject json = (JSONObject) o;
                    TbExcipientsData excipientsData = new TbExcipientsData();
                    // 逐个字段设置
                    excipientsData.setTemplateType("materialType");
                    excipientsData.setParamNameEn(json.getString("param_name_en"));
                    excipientsData.setParamKey(json.getString("param_key"));
                    TbTemplate tp = tbTemplateDao.getValueByParamKey("materialType", null, json.getString("param_key"));
                    excipientsData.setParamName(Objects.isNull(tp) ? null : tp.getParam_name());
                    excipientsData.setParamValue(json.getString("param_value"));
//            excipientsData.setParamType(json.getInteger("param_type"));
//            excipientsData.setLevel(json.getInteger("level"));
//            excipientsData.setSelectLevel(json.getInteger("select_level"));
//            excipientsData.setParentSelectId(json.getString("parent_select_id"));
//            excipientsData.setTip(json.getString("tip"));
//            excipientsData.setRemark(json.getString("remark"));
                    excipientsData.setCreateUser(userId);
                    excipientsData.setCreateTime(now);
//            excipientsData.setSort(json.getInteger("sort"));
//            excipientsData.setIsValue(json.getInteger("is_value"));
                    dataList.add(excipientsData);
                }
            }


            return queryKnowledgeBaseDataService.insertExcipientData(dataList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
    @PostMapping("/deleteExcipientsParams")
    public Result deleteExcipientsParams(@RequestBody String data) {
        try {
            List<Integer> idList = new ArrayList<>();
            JSONArray jsonArray = JSON.parseArray(data);
            for (Object jsonObject : jsonArray) {
                if (jsonObject instanceof JSONObject) {
                    JSONObject json = (JSONObject) jsonObject;
                    idList.add(json.getInteger("id"));
                }
            }
            return queryKnowledgeBaseDataService.deleteExcipientsParams(idList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
    @PostMapping("/updateExcipientData")
    public Result updateExcipientData(@RequestBody String data) {
        try {
            String userId = UserHeaderHolder.getUserId();
            Date now = new Date();
            JSONArray jsonArray = JSON.parseArray(data);
            if(Objects.isNull(jsonArray))
            {
                return ResultUtil.error(500, "辅料data为空", "null excipient data", null);
            }
            List<TbExcipientsData> dataList = new ArrayList<>();
            for(Object o : jsonArray )
            {
                if(o instanceof JSONObject)
                {
                    JSONObject json = (JSONObject) o;
                    TbExcipientsData excipientsData = new TbExcipientsData();
                    // 逐个字段设置
                    excipientsData.setTemplateType("materialType");
                    //excipientsData.setParamNameEn(json.getString("param_name_en"));
                    excipientsData.setParamKey(json.getString("param_key"));
                    excipientsData.setParamValue(json.getString("param_value"));
//            excipientsData.setParamType(json.getInteger("param_type"));
//            excipientsData.setLevel(json.getInteger("level"));
//            excipientsData.setSelectLevel(json.getInteger("select_level"));
//            excipientsData.setParentSelectId(json.getString("parent_select_id"));
//            excipientsData.setTip(json.getString("tip"));
//            excipientsData.setRemark(json.getString("remark"));
                    //excipientsData.setCreateUser(userId);
                    excipientsData.setUpdateUser(userId);
                    excipientsData.setUpdateTime(now);
                    String rowSort = json.getString("row_sort");
                    if (NumberUtils.isNumber(rowSort) && NumberUtils.toInt(rowSort, Integer.MIN_VALUE) != Integer.MIN_VALUE)
                    {
                        excipientsData.setRowSort(Integer.parseInt(rowSort));
                    }
                    String sort = json.getString("sort");
                    if (NumberUtils.isNumber(sort) && NumberUtils.toInt(sort, Integer.MIN_VALUE) != Integer.MIN_VALUE)
                    {
                        excipientsData.setSort(Integer.parseInt(sort));
                    }
//            excipientsData.setSort(json.getInteger("sort"));
//            excipientsData.setIsValue(json.getInteger("is_value"));
                    dataList.add(excipientsData);
                }
            }

            return queryKnowledgeBaseDataService.updateExcipientData(dataList);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
    @PostMapping("/deleteExcipientData")
    public Result deleteExcipientData(@RequestBody String data) {
        try {
            JSONObject jsonObject = JSON.parseObject(data);
            Integer rowSort = Integer.parseInt(jsonObject.getString("row_sort"));
            return queryKnowledgeBaseDataService.deleteExcipientData(rowSort);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/outPut")
    public Result outPutExipientData(@RequestBody String data) {
        try {
            JSONObject dataObject = JSON.parseObject(data);
            // 提取conditions
            JSONArray conditionsArray = dataObject.getJSONArray("conditions");
            List<Map<String, String>> keyValueMaps = new ArrayList<>();

            if (conditionsArray != null) {
                for (int i = 0; i < conditionsArray.size(); i++) {
                    JSONObject condition = conditionsArray.getJSONObject(i);
                    Map<String, String> map = new HashMap<>();
                    if(StringUtils.isEmpty(condition.getString("key")) && !StringUtils.isEmpty(condition.getString("value")))
                    {
                        return ResultUtil.error(500, "错误的键值对nullkey-to-value", "wrong key-value", null);
                    }
                    map.put("key", condition.getString("key"));
                    map.put("value", condition.getString("value"));
                    keyValueMaps.add(map);
                }
            }
            Result result = queryKnowledgeBaseDataService.outPutExipientData(keyValueMaps);
            if (result.getCode().equals(200)) {

                    String filepath = (String) result.getData();
                    File file = new File(filepath);
                    String fname = file.getName();
                    byte[] bytedata = null;
                    InputStream in = new FileInputStream(file);
                    bytedata = new byte[in.available()];
                    in.read(bytedata);
                    in.close();
                    Base64.Encoder encoder = Base64.getEncoder();
                    String base64 = encoder.encodeToString(bytedata);

                    Map<String, Object> map = new HashMap<>();
                    map.put("base64", base64);
                    map.put("fileName", fname);
                    return ResultUtil.success(map);
            } else {
                return result;
            }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("error : ", e);
                return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
            }
    }

    @PostMapping("/outPutExcipientTemplate")
    public Result outPutExcipientTemplate() {

            Map<String, List<String>> listMap = new LinkedHashMap<>();

            List<String> pkgList = new ArrayList<>();
            pkgList.add("排序");
            List<TbTemplate> tps = tbTemplateDao.getTbTemplateByLimit("materialType", null, 1);
            for(TbTemplate tp : tps)
            {
                pkgList.add(tp.getParam_name());
            }
            listMap.put("辅料库参数", pkgList);

            Result result = commonService.outputParamTemplate2(listMap, "辅料库模板");
            if (result.getCode().equals(200)) {
                try {
                    String filepath = (String) result.getData();
                    File file = new File(filepath);
                    String fname = file.getName();
                    byte[] bytedata = null;
                    InputStream in = new FileInputStream(file);
                    bytedata = new byte[in.available()];
                    in.read(bytedata);
                    in.close();
                    Base64.Encoder encoder = Base64.getEncoder();
                    String base64 = encoder.encodeToString(bytedata);

                    Map<String, Object> map = new HashMap<>();
                    map.put("base64", base64);
                    map.put("fileName", fname);
                    return ResultUtil.success(map);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("error : ", e);
                    return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
                }
            } else {
                return result;
            }
    }

    @PostMapping("/deleteExcipientDataList")
    public Result deleteExcipientDataList(@RequestBody String data) {
        try {
            List<Integer> idList = new ArrayList<>();
            JSONArray jsonArray = JSON.parseArray(data);
            for (Object jsonObject : jsonArray) {
                if (jsonObject instanceof JSONObject) {
                    JSONObject json = (JSONObject) jsonObject;
                    idList.add(json.getInteger("id"));
                }
            }
            return queryKnowledgeBaseDataService.deleteExcipientDataList(idList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ", e);
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    private static List<String> convertKeyListToStringList(JSONArray keyList, String keyName) {
        // 如果 keyList 为空或 null，返回空列表
        if (keyList == null || keyList.isEmpty()) {
            return new ArrayList<>();
        }

        // 创建 List 用于存储 knowledge_base_key 的值
        List<String> result = new ArrayList<>();

        // 遍历 JSONArray
        for (Object obj : keyList) {
            // 确保元素是 JSONObject
            if (obj instanceof JSONObject) {
                JSONObject jsonObject = (JSONObject) obj;
                // 提取 knowledge_base_key 的值
                String key = jsonObject.getString(keyName);
                // 如果 key 不为 null，添加到结果列表
                if (key != null) {
                    result.add(key);
                }
            }
            // 空对象或其他类型直接跳过
        }

        return result;
    }
}